package com.qingyun.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qingyun.common.constant.Constants;
import com.qingyun.common.core.domain.entity.SysUser;
import com.qingyun.common.core.domain.model.TiktokProxyVo;
import com.qingyun.common.core.domain.model.TiktokShopVo;
import com.qingyun.common.core.mybatisplus.core.ServicePlusImpl;
import com.qingyun.common.core.page.PagePlus;
import com.qingyun.common.core.page.TableDataInfo;
import com.qingyun.common.exception.CustomException;
import com.qingyun.common.exception.ServiceException;
import com.qingyun.common.utils.PageUtils;
import com.qingyun.security.utils.SecurityUtils;
import com.qingyun.shop.domain.TiktokShop;
import com.qingyun.shop.domain.TiktokUserShop;
import com.qingyun.shop.domain.bo.shop.TiktokShopAddBo;
import com.qingyun.shop.domain.bo.shop.TiktokShopEditBo;
import com.qingyun.shop.domain.bo.shop.TiktokShopQueryBo;
import com.qingyun.shop.domain.bo.shop.TiktokShopUserListBo;
import com.qingyun.shop.domain.vo.TiktokShopUserListVo;
import com.qingyun.shop.mapper.TiktokShopMapper;
import com.qingyun.shop.mapper.TiktokUserShopMapper;
import com.qingyun.shop.service.ITiktokShopService;
import com.qingyun.system.service.impl.SysUserServiceImpl;
import com.qingyun.tiktok.basis.response.video.VideoPoiRes;
import com.qingyun.tiktok.basis.service.interfaces.DyBasisService;
import com.qingyun.tiktok.common.enums.ApiPlatform;
import com.qingyun.tiktok.common.enums.ErrorCode;
import com.qingyun.tiktok.common.response.auth.ClientTokenRes;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * 商家Service业务层处理
 *
 * @author qingyun
 * @date 2021-09-04
 */
@Service
@AllArgsConstructor
public class TiktokShopServiceImpl extends ServicePlusImpl<TiktokShopMapper, TiktokShop, TiktokShopVo> implements ITiktokShopService {


	private final TiktokUserShopMapper tiktokUserShopMapper;

	private final SysUserServiceImpl userServiceImpl;

	private final MapperFacade mapperFacade;

	private final DyBasisService dyBasisService;


	@Override
	public TiktokShopVo queryById(Long id) {
		TiktokShop shop = baseMapper.selectById(id);
		TiktokShopVo map = mapperFacade.map(shop, TiktokShopVo.class);
		return map;
	}

	@Override
	public TableDataInfo<TiktokShopVo> queryPageList(TiktokShopQueryBo bo) {
		if(bo.getProxyId()==null){
			if(SecurityUtils.isProxy()){
				Long id = SecurityUtils.getProxy().getId();
				bo.setIds(Arrays.asList(id));
			}else if (SecurityUtils.isShop()) {
				bo.setId(SecurityUtils.getShop().getId());
			}
		}

		PagePlus<TiktokShop, TiktokShopVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo));
		return PageUtils.buildDataInfo(result);
	}

	@Override
	public List<TiktokShopVo> queryList(TiktokShopQueryBo bo) {
		return listVo(buildQueryWrapper(bo));
	}

	private LambdaQueryWrapper<TiktokShop> buildQueryWrapper(TiktokShopQueryBo bo) {
		LambdaQueryWrapper<TiktokShop> lqw = Wrappers.lambdaQuery();
		lqw.like(StringUtils.isNotBlank(bo.getName()), TiktokShop::getName, bo.getName());
		lqw.eq(bo.getId()!=null,TiktokShop::getId,bo.getId());
		lqw.eq(StringUtils.isNotBlank(bo.getLeader()), TiktokShop::getLeader, bo.getLeader());
		if (bo.getProxyId() != null && bo.getProxyId() != 1) {
			lqw.eq(TiktokShop::getProxyId,bo.getProxyId());
		}

		lqw.eq(StringUtils.isNotBlank(bo.getPhone()), TiktokShop::getPhone, bo.getPhone());
		lqw.eq(StringUtils.isNotBlank(bo.getEmail()), TiktokShop::getEmail, bo.getEmail());
		lqw.eq(bo.getStatus() != null, TiktokShop::getStatus, bo.getStatus());
		lqw.in(bo.getIds()!=null, TiktokShop::getProxyId,bo.getIds());

		lqw.orderByDesc(TiktokShop::getCreateTime);
		return lqw;
	}

	/**
	 * 根据商家id查询用户信息列表
	 *
	 * @param queryBo
	 */
	@Override
	public TableDataInfo<TiktokShopUserListVo> queryUserListByShopId(TiktokShopUserListBo queryBo) {
		if (queryBo.getShopId() == null) {
			//queryBo.setShopId(SecurityUtils.getSysLoginUser().getShop().getId());
			throw new ServiceException("请选择商户");
		}
		Page<TiktokShopUserListVo> result = baseMapper.selectUserListByShopId(PageUtils.buildPage(), queryBo);
		return PageUtils.buildDataInfo(result);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean insertByBo(TiktokShopAddBo bo) {
		TiktokShop shopAdd = BeanUtil.toBean(bo, TiktokShop.class);

		// 这里需要判断当前操作用户是平台还是代理商执行不同逻辑
		TiktokProxyVo proxy = SecurityUtils.getProxy();

		// 平台创建商户逻辑
		if (SecurityUtils.isManager()) {
			shopAdd.setProxyId(-1L);
			shopAdd.setProxyName("平台");
		// 代理商创建商户逻辑
		} else if (SecurityUtils.isProxy()) {
			shopAdd.setProxyId(proxy.getId());
			shopAdd.setProxyName(proxy.getName());
		} else {
			throw new CustomException("您没有创建下级商家的权限，请平台申请成为代理商");
		}

		// 创建商户
		save(shopAdd);
		// 创建一条商户账户信息的记录

		return Boolean.TRUE;
	}

	@Override
	@Transactional
	@CacheEvict(cacheNames = "GetAcitvity", allEntries=true)
	public Boolean updateByBo(TiktokShopEditBo bo) {
		TiktokShop update = BeanUtil.toBean(bo, TiktokShop.class);
		updateShopNameByShopId(update.getId(),update.getName());

		return updateById(update);
	}


	@Override
	public Boolean deleteWithValidByIds(Long id, Boolean isValid) {
		return null;
	}

	@Override
	@Transactional
	public Boolean configUser(SysUser user, Long shopId) {
		user.setUserType(Constants.SHOP_USER);

		userServiceImpl.insertUser(user);

//		userServiceImpl.insertUserPost(user);
//		userServiceImpl.insertUserRole(user);

		// 插入一条用户与商家关联记录
		TiktokUserShop tiktokUserShop = new TiktokUserShop();
		tiktokUserShop.setUserId(user.getUserId());
		tiktokUserShop.setShopId(shopId);
		tiktokUserShopMapper.insert(tiktokUserShop);

		return Boolean.TRUE;
	}

	/**
	 * 启用/停用商户
	 *
	 * @param id
	 * @param status
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean startOrStop(Long id, Integer status) {
		TiktokShop shop = new TiktokShop();
		shop.setId(id);
		shop.setStatus(status);
		return this.baseMapper.updateById(shop) > 0;
	}
	@Override
	public Boolean updateShopNameByShopId(Long shopId, String ShopName) {

		return baseMapper.updateShopNameByShopId(shopId,ShopName);
	}

	@Override
	public List<VideoPoiRes.Poi> searchPOI(String address) {
		ClientTokenRes.ClientTokenResData clientTokenResData = dyBasisService.getAuth2Service().authClientToken(ApiPlatform.DOU_YIN);
		if(clientTokenResData.getErrorCode()== ErrorCode.SUCCESS.getValue()){
			String clientToken = clientTokenResData.getAccessToken();
			VideoPoiRes.VideoPoiResData res = dyBasisService.getVideoService().searchPOI(clientToken,address);
			if(res.getErrorCode()== ErrorCode.SUCCESS.getValue()){
				return res.getPois();
			}
		}
		return null;
	}

}

